package com.freesky.provider.order.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.freesky.common.constant.CountConstant;
import com.freesky.common.vo.ChartData;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.vo.VOOrderChartData;
import com.freesky.provider.order.service.IStatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: 陈玉林
 * @date: 2018/12/17 16:13
 * @description: 订单统计服务
 */
@RestController
@RequestMapping("/statistic/order")
public class StatisticController {

    @Autowired
    private IStatisticService statisticService;

    @GetMapping
    public JSONResponse countOrder(
            @RequestParam(value = "type") int type,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "year", required = false) int year) {

        ChartData data = new ChartData();
        Date startDate = null, endDate = null;
        if (type == CountConstant.CUSTOM_DATE) {
            startDate = DateUtil.beginOfDay(DateUtil.parse(startTime));
            endDate = DateUtil.endOfDay(DateUtil.parse(endTime));
            long betweenDay = DateUtil.between(startDate, endDate, DateUnit.DAY);
            if (betweenDay > 31) {
                return JSONResponseDiretor.buildErrorJSONResponse("所选日期范围过长，最多不能超过31天");
            }
        }
        List<VOOrderChartData> list = statisticService.getOrderCountData(type, startDate, endDate, year);
        List<Object> xDatas = new ArrayList<>();
        List<Object> yDatas = new ArrayList<>();
        BigDecimal countAll = new BigDecimal("0");
        for (VOOrderChartData orderData : list) {
            if (type == CountConstant.CUSTOM_YEAR) {
                xDatas.add(DateUtil.format(orderData.getTime(), "yyyy-MM"));
            } else {
                xDatas.add(DateUtil.formatDate(orderData.getTime()));
            }
            yDatas.add(orderData.getMoney());
            countAll = countAll.add(orderData.getMoney());
        }
        data.setXDatas(xDatas);
        data.setYDatas(yDatas);
        data.setCountAll(countAll);
        return JSONResponseDiretor.buildSuccessJSONResponse(data);
    }
}
